package com.cmwa.scbp.base.config.web;

import java.util.Date;

import org.springframework.core.convert.converter.Converter;

import com.cmwa.scbp.utils.DateUtils;

/**
 * 请求参数中的日期字符串自动转换为Date对象
 * @author ex-zuotc
 *
 */
public class StringToDateConverter implements Converter<String, Date> {

	@Override
	public Date convert(String source) {
		Date result = null;
		if (source != null && source.length() != 0) {
			try {
				if (source.length() == 10) {
					// YYYY-MM-DD
					result = DateUtils.parseDate(source, DateUtils.DATE_FORMAT_yMd_EN);
				} else if (source.length() == 19) {
					// YYYY-MM-DD HH:MM:SS
					result = DateUtils.parseDate(source, DateUtils.DATE_FORMAT_yMdHms_EN);
				} else {
					throw new IllegalArgumentException("转换日期失败: 日期长度不符合要求!");
				}
			} catch (Exception ex) {
				throw new IllegalArgumentException("转换日期失败: " + ex.getMessage(), ex);
			}
		}
		return result;
	}

}
